﻿/*
   Copyright 2014 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using Flower.Services;
using Flower.Services.Data;
using Jurassic;
using Jurassic.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flower.Directory.Util;
using Flower.Directory.Scripting.Functions.Messaging;
using Flower.Directory.Scripting.Functions.Waiting;

namespace Flower.Directory.Scripting.Functions.Locking
{
    internal class Lock : ClrFunction
    {
        public Lock(ScriptEngine engine)
            : base(engine.Function.InstancePrototype, "__lock", engine.Function.InstancePrototype)
        {
        }

        [JSCallFunction]
        public ObjectInstance Exec(ArrayInstance resources, string owner, string pid)
        {
            try
            {
                IDirectory dir = Engine.GetDirectory();

                var lockedResources = Engine.Array.Construct();
                var owners = Engine.Array.Construct();

                var result = 
                    Exec(dir, resources.ElementValues.Select(el => el.ToString()).ToArray(), owner, pid);

                foreach (string el in (IList<string>)result["resources"])
                {
                    lockedResources.Push(el);
                }

                foreach (string el in (IList<string>)result["owners"])
                {
                    owners.Push(el);
                }

                return 
                    Engine
                        .Object
                        .Construct()
                        .Set("resources", lockedResources)
                        .Set("owners", owners);
            }
            catch (JavaScriptException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new JavaScriptException(Engine, "Error", ex.Message, ex);
            }
        }

        [ClrScript]
        public static Dictionary<string, object> Exec(IDirectory dir, IList<string> resources, string owner, string pid)
        {
            var lockedResources = new List<string>();
            var owners = new List<string>();

            foreach (string res in resources)
            {
                Util.DemandLock.Acquire(res);

                var currentOwners =
                    dir.GetChildren(res, DirectoryEntryTypes.Message, SortProperty.Default, SortOrder.Asc, 0, long.MaxValue);

                bool canLock = true;

                if (currentOwners.Count > 0 && currentOwners[0].Name != owner)
                {
                    canLock = false;
                }

                if (canLock)
                {
                    if (currentOwners.Count > 0)
                    {
                        var msg = (Message)currentOwners[0];
                        var data = msg.Data;
                        msg.Data =
                            (data.To<int>() + 1).ToBlob(data.Format);

                        dir.Save(res, msg);
                    }
                    else
                    {
                        EnqueueMessage.Exec(dir, res, new Message { Name = owner, Data = (1).ToBlob(BlobFormat.BinXml) }, pid);
                    }
                }
                else
                {
                    lockedResources.Add(res);

                    foreach (var o in currentOwners)
                    {
                        owners.Add(o.Name);
                    }

                    Wait.Exec(dir, res, pid, WaitingFolders.PutWaiters);
                }
            }

            return new Dictionary<string, object>
            {
                { "resources", lockedResources },
                { "owners", owners }
            };
        }
    }
}
